﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace blackhouse.Translator.Business.GlobalResources {
    public class ResxTranslatorResourceManager : ITranslatorResourceManager {

        #region Fields

        private readonly string resourcesDirectory;
        private ITranslatorResource[] resources;

        #endregion

        #region Constructors

        public ResxTranslatorResourceManager(string resourcesLocation) {
            this.resourcesDirectory = resourcesLocation;
            if (!this.resourcesDirectory.EndsWith(@"\")) this.resourcesDirectory += @"\";

        }

        #endregion

        #region Methods

        public ITranslatorResource[] GetResources() {
            if (this.resources == null) {
                FileInfo configurationFile = new FileInfo(this.resourcesDirectory + "translatefiles.config");
                if (configurationFile.Exists) {
                    using (FileStream fs = configurationFile.OpenRead()) {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(fs);
                        XmlNodeList xnl = xmlDoc.SelectNodes("/files/file");
                        List<ResxTranslatorResource> resources = new List<ResxTranslatorResource>(xnl.Count);
                        foreach (XmlNode xn in xnl) {
                            string name = xn.Attributes["name"].Value;
                            string resxName = xn.Attributes["resourcename"].Value;
                            ResxTranslatorResource resource = new ResxTranslatorResource(this.resourcesDirectory, resxName, name);
                            if (resource.Exist)
                                resources.Add(resource);
                        }
                        this.resources = resources.ToArray();

                    }
                } else
                    this.resources = new ITranslatorResource[0];
            }
            return this.resources;
        }

        #endregion

    }
}
